package dev.hitools.utils.kts

import android.app.Activity
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import dev.hitools.utils.base.R
import dev.hitools.utils.kts.ContextExt.findColor
import dev.hitools.utils.kts.binding.ActivityBinding


@Suppress("unused")
object ActivityExt {
    /**
     * inflate 方便实现
     * @param layoutRes layout的Id
     */
    fun Activity.inflate(layoutRes: Int): View {
        return LayoutInflater.from(this).inflate(layoutRes, null)
    }


    /**
     * 隐藏一个Fragment
     */
    fun AppCompatActivity.hideFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.hide(fragment)
        transaction.commit()
    }

    /**
     * 设置状态栏的颜色通过Resource 来进行设置
     */
    fun AppCompatActivity.setStatusBarColorRes(@ColorRes color: Int) {
        setStatusBarColor(findColor(color))
    }

    /**
     * 设置状态栏的颜色
     */
    fun AppCompatActivity.setStatusBarColor(@ColorInt color: Int) {
        val window = window
        window.statusBarColor = color
    }

    /**
     * 全屏模式 设置一个Activity 为一个全屏模式
     * @param navigationBar 是否同时隐藏 navigationBar
     */
    fun AppCompatActivity.fullWindow(navigationBar: Boolean = true) {
        setStatusBarColor(Color.TRANSPARENT)

        val control = WindowCompat.getInsetsController(window, window.decorView)
        if (navigationBar) {
            control.hide(WindowInsetsCompat.Type.systemBars())
        } else {
            control.hide(WindowInsetsCompat.Type.statusBars())
        }
    }

    /**
     * 是否是浅色状态栏
     */
    inline val AppCompatActivity.isLightStatusBars: Boolean
        get() {
            val control = WindowCompat.getInsetsController(window, window.decorView)
            return control.isAppearanceLightStatusBars
        }

    /**
     * 设置一个 Activity为普通模式
     */
    @JvmOverloads
    fun AppCompatActivity.normalWindow(color: Int? = null, navigationBar: Boolean = true) {
        val statusColor = color ?: findColor(R.color.color_accent)
        setStatusBarColor(statusColor)

        val control = WindowCompat.getInsetsController(window, window.decorView)
        if (navigationBar) {
            control.show(WindowInsetsCompat.Type.systemBars())
        } else {
            control.show(WindowInsetsCompat.Type.statusBars())
        }
    }


    /**
     * 方便获取ViewDataBinding
     */
    inline fun <reified T : ViewBinding> AppCompatActivity.binding() = ActivityBinding(T::class.java, this)

}
